package com.microservice.salmon.oauth.code.impl;

import com.microservice.salmon.oauth.code.ValidateCode;
import com.microservice.salmon.oauth.code.ValidateCodeException;
import com.microservice.salmon.oauth.code.ValidateCodeRepository;
import com.microservice.salmon.oauth.code.ValidateCodeType;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;

import java.util.concurrent.TimeUnit;

@Component
public class AppValidateCodeRepository implements ValidateCodeRepository {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Override
    public void save(ServletWebRequest request, ValidateCode validateCode, ValidateCodeType validateCodeType) {
        // 30分钟过期,但验证码也有过期时间，和redis存储的过期时间不是一个时间, 验证码的时间必须小于 30分钟
        redisTemplate.opsForValue().set(buildKey(request, validateCodeType), validateCode, 30, TimeUnit.MINUTES);
    }

    @Override
    public ValidateCode get(ServletWebRequest request, ValidateCodeType validateCodeType) {
        Object value = redisTemplate.opsForValue().get(buildKey(request, validateCodeType));
        if(value == null) {
            return null;
        }
        return (ValidateCode) value;
    }

    @Override
    public void remove(ServletWebRequest request, ValidateCodeType validateCodeType) {
        redisTemplate.delete(buildKey(request, validateCodeType));
    }

    private String buildKey(ServletWebRequest request, ValidateCodeType validateCodeType) {
        String deviceId = request.getParameter("deviceId");
        if(StringUtils.isBlank(deviceId)) {
            throw new ValidateCodeException("请在请求URL中携带deviceId");
        }
        return "code:" + validateCodeType.toString().toLowerCase() + ":" + deviceId;
     /*   String mobile = request.getParameter(SecurityConstants.DEFAULT_PARAMETER_NAME_MOBILE);
        if(StringUtils.isBlank(mobile)) {
            throw new ValidateCodeException("确定手机号的传输字段为：" + SecurityConstants.DEFAULT_PARAMETER_NAME_MOBILE);
        }
        return "code:" + validateCodeType.toString().toLowerCase() + ":" + mobile;*/
    }
}
